#!/usr/bin/python
# -*- coding: UTF-8 -*-
import re,os
import pymysql.cursors
import collections
# import sys
# reload(sys)
# sys.setdefaultencoding('utf8');
fieldLowerCase = False
dbname = 'power'
gofile='/core/dao/table/Table.go'
def getCon():
	connection = pymysql.connect(host='localhost',
	                             user='root',
	                             password='123456',
	                             db=dbname,
	                             port=3306,
	                             charset='utf8',
	                             cursorclass=pymysql.cursors.DictCursor)
	return connection

# for v in ks:
# 	print re.sub(r'^\w' , lambda x : x.group(0).upper() , v)

def capital(s) :
	return re.sub(r'^\w' , lambda x : x.group(0).upper() , s)
def lower(s) :
	return re.sub(r'^\w' , lambda x : x.group(0).lower() , s)


def getTableDesc():
	db = getCon()
	cursor = db.cursor()
	cursor.execute("show tables")
	results = cursor.fetchall()
	tables = {}
	for row in results:
		table = row["Tables_in_"+dbname]
		cursor.execute("show full columns from `"+table+"`")
		cols = cursor.fetchall()
		tables[table] = cols
	tableComments = {}
	cursor.execute("SELECT table_comment,table_name FROM INFORMATION_SCHEMA.TABLES where table_schema = '"+dbname+"'")
	results = cursor.fetchall()
	for row in results :
		# print("row--->" ,row)
		tableComments[row["TABLE_NAME"]] = row["TABLE_COMMENT"]
	db.close()
	return (tables ,tableComments)

def mapType(mysqlType  , nullable  , comment ,name):
	m = re.match(r"type:(\w+)" , comment)
	if m :
		t= m.group(1)
		if t != "" :
			return t
	if -1!= mysqlType.find("bigint") :
		if nullable :
			return "null.Int"
		return "int64"
	if -1!= mysqlType.find("tinyint") :
		if nullable :
			return "null.Bool"
		return "bool"
	if -1!= mysqlType.find("float") :
		if nullable :
			return "null.Float"
		return "float32"
	if -1!= mysqlType.find("int") :
		if nullable :
			return "null.Int"
		return "int"
	if -1!= mysqlType.find("date") :
		if nullable :
			return "null.Time"
		return "time.Time"
	if -1!= mysqlType.find("char") or -1!= mysqlType.find("text") :
		if nullable :
			if comment.startswith("hfs"):
				return "hfsc.NullHfsLink"
			return "null.String"
		if comment.startswith("hfs"):
			return "hfsc.HfsLink"
		return "string"
	return "string"

# col: {'Field': 'name', 'Type': 'varchar(30)', 'Collation': 'utf8mb4_general_ci', 'Null': 'NO', 'Key': 'UNI', 'Default': None, 'Extra': '', 'Privileges': 'select,insert,update,references', 'Comment': ''}
# col: {'Field': 'uid', 'Type': 'int(11)', 'Collation': None, 'Null': 'NO', 'Key': 'UNI', 'Default': None, 'Extra': '', 'Privileges': 'select,insert,update,references', 'Comment': ''}
def table2Struct(table , cols):
	s = "type "+table+" struct {\n"
	for c in cols:
		if c["Field"]=="id" :
			if -1 == c["Extra"].find('auto_increment') :
				print("table:"+table+" id not auto_increment")
		s+= "\t//"+c["Type"]
		if c["Comment"] :
			s+= " "+re.sub(r"[\r\n]+" , r"\n\t//" ,c["Comment"])
		s+="\n"
		field = c["Field"]
		s+= "\t"+capital(field)+" "+mapType(c["Type"],"YES"==c["Null"],c["Comment"] ,field)
		if fieldLowerCase :
			s += ' `json:"'+lower(field)+'"`' # `json:"id"`
		s+="\n"
		if "YES"==c["Null"] :
			print(table+"."+c["Field"]+" is nullable field")
	s+= "}\n"

	return s



def trans():
	root  = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
	print("project root dir:",root)
	tableFile  = root+gofile
	print("write to table file:",tableFile)
	if not os.path.exists(os.path.dirname(tableFile)) :
		os.makedirs(os.path.dirname(tableFile))
	file = open(root+gofile,"w+" , encoding="utf8")
	# fnFile = open(root+"/service/table/TableBasicFn.go","w+", encoding="utf8")
	file.write("package table\n\n")
	file.write('import "gopkg.in/guregu/null.v3"\n\n')
	# fnFile.write("package table\n")
	# fnFile.write('''
# import (
# 	"good/base/exception"
# 	"github.com/go-gorp/gorp"
# )
	# '''
	# )
	(tables,tableComments) = getTableDesc()
	for k in sorted(tables) :
		if k.startswith('_'):
			continue
		v = tables[k]
		if tableComments[k]:
			file.write("//"+re.sub(r"[\r\n]+" , r"\n//" ,tableComments[k])+"\n")
		file.write(table2Struct(k,v))
		#genTableFns(fnFile,k,v)
	file.close()
	# fnFile.close()

trans()